package activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;

import net.ck.hzq.R;

import org.greenrobot.eventbus.EventBus;

import Utils.AccountUtils;
import Utils.FileUtil;
import Utils.HelloWordModel;
import Utils.OCRUtils;
import Utils.ToastUtil;
import activity.glide.GlideApp;
import base.BaseActivity;
import dao.BaseOutput;
import dao.GetUrlOutput;
import dao.SubmitWorkOrderOutput;
import dao.WorkOrderHandleInput;
import dialog.FlowRuleDialog;
import event.LoginEvent;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WorkOrderHandleActivity extends BaseActivity implements View.OnClickListener {

    private static final int REQUEST_ID_FRONT = 1;
    private static final int REQUEST_ID_BACK = 2;
    private static final int REQUEST_ID_HAND = 3;
    private static final int REQUEST_CARD_FRONT = 4;
    private static final int REQUEST_CARD_BACK = 5;
    private static final int REQUEST_CARD_HAND = 6;
    private static final int REQUEST_PAY_PROVE = 7;
    private static final int REQUEST_PAY_PROVE_HAND = 8;
    private static final int REQUEST_PAY_TICKET = 9;

    private int mWorkOrderId;

    private ImageView idFront, idBack, idHand, cardFront, cardBack, cardHand, payProve, payProveHand, payTicket;
    private String base64_idFront, base64_idBack, base64_idHand, base64_cardFront,
            base64_cardBack, base64_cardHand, base64_payProve, base64_payProveHand, base64_payTicket;

    public static void start(Context context, int workOrderId) {
        Intent intent = new Intent(context, WorkOrderHandleActivity.class);
        intent.putExtra("workOrderId", workOrderId);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_work_order_handle;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mWorkOrderId = getIntent().getIntExtra("workOrderId", 0);

        idFront = findViewById(R.id.iv_id_front);
        idBack = findViewById(R.id.iv_id_back);
        idHand = findViewById(R.id.iv_id_hand);
        cardFront = findViewById(R.id.iv_card_front);
        cardBack = findViewById(R.id.iv_card_back);
        cardHand = findViewById(R.id.iv_card_hand);
        payProve = findViewById(R.id.iv_pay_prove);
        payProveHand = findViewById(R.id.iv_pay_prove_hand);
        payTicket = findViewById(R.id.iv_pay_ticket);

        idFront.setOnClickListener(this);
        idBack.setOnClickListener(this);
        idHand.setOnClickListener(this);
        cardFront.setOnClickListener(this);
        cardBack.setOnClickListener(this);
        cardHand.setOnClickListener(this);
        payProve.setOnClickListener(this);
        payProveHand.setOnClickListener(this);
        payTicket.setOnClickListener(this);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.submit_btn).setOnClickListener(this);
        findViewById(R.id.pay_prove_template).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_id_front:
                OCRUtils.startIDCardFront(this, REQUEST_ID_FRONT);
                break;
            case R.id.iv_id_back:
                OCRUtils.startIDCardBack(this, REQUEST_ID_BACK);
                break;
            case R.id.iv_id_hand:
                OCRUtils.startCapture(this, FileUtil.getSaveFileFace(this), REQUEST_ID_HAND);
                break;
            case R.id.iv_card_front:
                OCRUtils.startBankCard(this, REQUEST_CARD_FRONT);
                break;
            case R.id.iv_card_back:
                OCRUtils.startBankCardBack(this, REQUEST_CARD_BACK);
                break;
            case R.id.iv_card_hand:
                OCRUtils.startCapture(this, FileUtil.getExternalImageFile("card_hand.jpg"), REQUEST_CARD_HAND);
                break;
            case R.id.iv_pay_prove:
                OCRUtils.startCapture(this, FileUtil.getExternalImageFile("pay_prove.jpg"), REQUEST_PAY_PROVE);
                break;
            case R.id.iv_pay_prove_hand:
                OCRUtils.startCapture(this, FileUtil.getExternalImageFile("pay_prove_hand.jpg"), REQUEST_PAY_PROVE_HAND);
                break;
            case R.id.iv_pay_ticket:
                OCRUtils.startCapture(this, FileUtil.getExternalImageFile("pay_ticket.jpg"), REQUEST_PAY_TICKET);
                break;
            case R.id.pay_prove_template:
                showTemplate();
                break;
            case R.id.submit_btn:
                submit();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_ID_FRONT) {
            GlideApp.with(this)
                    .load(FileUtil.getSaveFileSfzzm(this))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(idFront);
            base64_idFront = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getSaveFileSfzzm(this).getAbsolutePath());
        }
        if (requestCode == REQUEST_ID_BACK) {
            GlideApp.with(this)
                    .load(FileUtil.getSaveFileSfzfm(this))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(idBack);
            base64_idBack = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getSaveFileSfzfm(this).getAbsolutePath());
        }
        if (requestCode == REQUEST_ID_HAND) {
            GlideApp.with(this)
                    .load(FileUtil.getSaveFileFace(this))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(idHand);
            base64_idHand = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getSaveFileFace(this).getAbsolutePath());
        }
        if (requestCode == REQUEST_CARD_FRONT) {
            GlideApp.with(this)
                    .load(FileUtil.getSaveFile(this))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(cardFront);
            base64_cardFront = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getSaveFile(this).getAbsolutePath(), 1500);
        }
        if (requestCode == REQUEST_CARD_BACK) {
            GlideApp.with(this)
                    .load(FileUtil.getBankBackFile(this))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(cardBack);
            base64_cardBack = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getBankBackFile(this).getAbsolutePath());
        }
        if (requestCode == REQUEST_CARD_HAND) {
            GlideApp.with(this)
                    .load(FileUtil.getExternalImageFile("card_hand.jpg"))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(cardHand);
            base64_cardHand = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getExternalImageFile("card_hand.jpg")
                    .getAbsolutePath());
        }
        if (requestCode == REQUEST_PAY_PROVE) {
            GlideApp.with(this)
                    .load(FileUtil.getExternalImageFile("pay_prove.jpg"))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(payProve);
            base64_payProve = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getExternalImageFile("pay_prove.jpg")
                    .getAbsolutePath(), 1000);
        }
        if (requestCode == REQUEST_PAY_PROVE_HAND) {
            GlideApp.with(this)
                    .load(FileUtil.getExternalImageFile("pay_prove_hand.jpg"))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(payProveHand);
            base64_payProveHand = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getExternalImageFile("pay_prove_hand" +
                    ".jpg").getAbsolutePath());
        }
        if (requestCode == REQUEST_PAY_TICKET) {
            GlideApp.with(this)
                    .load(FileUtil.getExternalImageFile("pay_ticket.jpg"))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(payTicket);
            base64_payTicket = "data:image/jpg;base64," + FileUtil.compress(FileUtil.getExternalImageFile("pay_ticket.jpg")
                    .getAbsolutePath(), 1000);
        }
    }

    private void submit() {
        if (TextUtils.isEmpty(base64_idFront)
                || TextUtils.isEmpty(base64_idBack)
                || TextUtils.isEmpty(base64_idHand)
                || TextUtils.isEmpty(base64_cardFront)
                || TextUtils.isEmpty(base64_cardFront)
                || TextUtils.isEmpty(base64_cardHand)
                || TextUtils.isEmpty(base64_payProve)
                || TextUtils.isEmpty(base64_payProveHand)) {
            ToastUtil.showNormal(this, "请上传所有必要证明");
            return;
        }

        showProgressDialog();
        WorkOrderHandleInput input = new WorkOrderHandleInput();
        input.customId = AccountUtils.getCustomId();
        input.workOrderId = mWorkOrderId;
        input.idCardFront = base64_idFront;
        input.idCardBack = base64_idBack;
        input.holdIdCardFront = base64_idHand;
        input.bankFront = base64_cardFront;
        input.bankBack = base64_cardBack;
        input.holdBankFront = base64_cardHand;
        input.payment = base64_payProve;
        input.holdPayment = base64_payProveHand;
        if (!TextUtils.isEmpty(base64_payTicket)) {
            input.payableBills = base64_payTicket;
        }
        HelloWordModel.getInstance(this).handleWorkOrder(input).enqueue(new Callback<SubmitWorkOrderOutput>() {
            @Override
            public void onResponse(Call<SubmitWorkOrderOutput> call, Response<SubmitWorkOrderOutput> response) {
                dismissProgressDialog();
                try {
                    if (response.body() != null && "401".equals(response.body().result)) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else if (response.body() != null && response.body().msg.equals("success")) {
                        ToastUtil.showNormal(WorkOrderHandleActivity.this, "提交成功");
                        finish();
                    } else {
                        ToastUtil.showNormal(WorkOrderHandleActivity.this, response.body().msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<SubmitWorkOrderOutput> call, Throwable t) {
                dismissProgressDialog();
                ToastUtil.showNormal(WorkOrderHandleActivity.this, "提交失败");
            }
        });
    }

    private void showTemplate() {
        HelloWordModel.getInstance(this).getPayProveTemplate().enqueue(new Callback<BaseOutput<GetUrlOutput>>() {
            @Override
            public void onResponse(Call<BaseOutput<GetUrlOutput>> call, Response<BaseOutput<GetUrlOutput>> response) {
                BaseOutput<GetUrlOutput> body = response.body();
                if (body == null) {
                    return;
                }
                try {
                    if (response.body() != null && "401".equals(response.body().result)) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else if ("success".equals(body.msg) && body.data != null) {
                        if (body.data.items != null) {
                            FlowRuleDialog dialog = FlowRuleDialog.newInstance(body.data.items);
                            dialog.show(getSupportFragmentManager(), "");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<BaseOutput<GetUrlOutput>> call, Throwable t) {
            }
        });
    }

}
